/* eslint-disable no-unused-vars */
var content = chrome.extension.getURL('js/content.js')
var script = document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', content)
// document.body.appendChild(script)

// eslint-disable-next-line no-unused-vars
function injectScript (src, buildIn = false) {
  var script = document.createElement('script')
  script.setAttribute('type', 'text/javascript')
  script.setAttribute('src', src)
  document.body.appendChild(script)
}

// 注入jquery
// injectScript('https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js')

/**
 *
 * @param {Number} where [0|1] 1滚动到底部，0滚动到顶部
 */
var goToWhere = function (where, callback) {
  var me = {}
  me.site = []
  me.sleep = me.sleep ? me.sleep : 260
  me.fx = me.fx ? me.fx : 26
  clearInterval(me.interval)
  var dh = document.documentElement.scrollHeight || document.body.scrollHeight
  var height = where ? dh : 0
  me.interval = setInterval(function () {
    var top = document.documentElement.scrollTop || document.body.scrollTop
    var speed = (height - top) / me.fx
    if (speed === me.site[0]) {
      window.scrollTo(0, height)
      clearInterval(me.interval)
      callback && callback()
    }
    window.scrollBy(0, speed)
    me.site.unshift(speed)
  }, me.sleep)
}

const NavListMapper = {
  getNavList () {
    return JSON.parse(localStorage.getItem('navList') || '[]')
  },
  storeNavList (navList) {
    localStorage.setItem('navList', JSON.stringify(navList))
  },
  addNav (nav) {
    let navList = this.getNavList()
    let include = false
    for (const item of navList) {
      if (item.title === nav.title) {
        include = true
      }
    }
    if (!include) {
      navList.push(nav)
      this.storeNavList(navList)
    }
  }
}

var $ = window.$

/**
   * 查询页面下载链接
   * @returns {Array} 返回拼装了域名并URL编码后的下载链接，示例: http://alist.xiaoya.pro/d/%E9%9F%B3%E4%B9%90
   */
const startDownload = function () {
  goToWhere(1, () => {
    findAllNav()

    function switchTab () {

    }
    // 依次点击二级导航，显示出未显示的nav
    $('#content > div.d-flex.slider-menu-father.mb-4 > div > ul > li > a').each(function (index, item) {
    // 将tab存入队列中。因为切换图片后需要睡眠2秒，让接口返回新的nav数据并加载图片
      switchTabQueue.push(item)
    // let jqObj = $(item).html(`<span>${$(item).text()}</span>`)
    // jqObj.find('span').click()
    // findAllNav()
    })
    // 依次点击二级导航，显示出未显示的nav
    $('#content > div.content > div > div > div > div.slider_menu.mini_tab.ajax-list-home.into > ul > li > a').each(function (index, item) {
    // 将tab存入队列中。因为切换图片后需要睡眠2秒，让接口返回新的nav数据并加载图片
      switchTabQueue.push(item)
    // let jqObj = $(item).html(`<span>${$(item).text()}</span>`)
    // jqObj.find('span').click()
    // findAllNav()
    })
  })
}

// 切换tab队列，存入DOM对象
var switchTabQueue = []
// 跳转详情页队列，存入jquery对象
var openDetailQueue = []
// 详情页队列
var detailUrlQueue = []

// 详情页队列消费者
function openDetail () {
  if (openDetailQueue.length > 0) {
    let firstItem = openDetailQueue.shift()
    console.log(firstItem)
    firstItem.click()
  }
  if (detailUrlQueue.length > 0) {
    let firstItem = detailUrlQueue.shift()
    // 给插件发送打开详情页消息
    chrome.runtime.sendMessage({
      type: 'tabs.create',
      url: firstItem
    }, function (response) {
      console.log('收到来自后台的回复：' + response)
    })
  }

  setTimeout(() => {
    openDetail()
  }, 1000)
}
openDetail()

// 切换tab队列消费者
function switchTabCustomer () {
  if (switchTabQueue.length > 0) {
    let firstItem = switchTabQueue.shift()
    window.scrollTo(0, $(firstItem).offset().top)
    let jqObj = $(firstItem).html(`<span>${$(firstItem).text()}</span>`)
    jqObj.find('span').click()
    // findAllNav()
    // 切换tab后等待接口返回数据和图片加载完成
    setTimeout(() => {
      findAllNav(true)
    }, 5000)
  } else {
    setTimeout(() => {
      switchTabCustomer()
    }, 1000)
  }
}
switchTabCustomer()

// 查找整个页面当前显示的所有导航
function findAllNav (switchTab = false) {
  $('.url-card').each((index, item) => {
    // console.log($(item))
    // console.log($(item).find('div.url-info.flex-fill > div > strong'))
    let navTitle = $(item).find('div.url-info.flex-fill > div > strong').html()
    // console.log('navTitle: ' + navTitle)

    let navDesc = $(item).find('div.url-info.flex-fill > p').html()
    // console.log('navDesc: ' + navDesc)

    let iconUrl = $(item).find('div.url-img > img').attr('src')
    // console.log('navIconUrl: ' + iconUrl)

    let nav = {
      title: navTitle,
      desc: navDesc,
      iconUrl: iconUrl
    }

    // 查找分类信息
    if ($(item).parent().parent().hasClass('content-layout')) { // 判断是否只有一个大分类
      let categoryName = $(item).parent().prev().children('h4').text()
      nav.categoryName = categoryName.replaceAll('\n', '').replaceAll(' ', '')
    } else if ($(item).parent().parent().hasClass('tab-pane')) { // 判断是否是tab模式菜单
      let categoryName = $(item).parent().parent().parent().prev().prev().text()
      let subCategoryName = $(item).parent().parent().parent().prev().find('.nav-link.active').text()
      nav.categoryName = categoryName.replaceAll('\n', '').replaceAll(' ', '')
      nav.subCategoryName = subCategoryName.replaceAll('\n', '').replaceAll(' ', '')

      // console.log(categoryName, subCategoryName)
      // console.log('nav: ', nav)
    }

    // console.log('nav: ', nav)

    NavListMapper.addNav(nav)

    // console.log($(item).find('.card-body'))
    // $(item).find('.card-body').click()
    // openDetailQueue.push($(item).find('.card-body'))

    // 将详情页链接加入队列
    detailUrlQueue.push($(item).find('a').attr('href'))
  })

  // 接着切换下一个tab
  if (switchTab) {
    setTimeout(() => {
      switchTabCustomer()
    }, 3000)
  }
}

function parseDetailPage () {
  let navTitle = $('#content > div.row.site-content.py-4.py-md-5.mb-xl-5.mb-0.mx-xxxl-n5 > div.col.mt-4.mt-sm-0 > div > h1').html()
  console.log('navTitle: ' + navTitle)

  let siteUrl = $('#content > div.row.site-content.py-4.py-md-5.mb-xl-5.mb-0.mx-xxxl-n5 > div.col.mt-4.mt-sm-0 > div > div > div.site-go.mt-3 > span > a').attr('href')
  console.log('siteUrl: ' + siteUrl)

  let otherSite = []
  $('#content > div.row.site-content.py-4.py-md-5.mb-xl-5.mb-0.mx-xxxl-n5 > div.col.mt-4.mt-sm-0 > div > div > div.spare-site.mb-3 > a').each((index, item) => {
    let otherSiteUrl = $(item).attr('href')
    let otherSiteTitle = $(item).find('span').text()
    otherSite.push({
      title: otherSiteTitle,
      url: otherSiteUrl
    })
  })
  console.log('otherSite: ', otherSite)

  let navLongDesc = $('#content > main > div > div > div.panel.site-content.card.transparent > div > div.panel-body.single.my-4 > p').text()
  console.log('navLongDesc: ' + navLongDesc.trim())

  // 读取storage中的nav数据，补充直达链接等数据
  let navList = NavListMapper.getNavList()
  for (const item of navList) {
    if (item.title === navTitle) {
      item.siteUrl = siteUrl
      item.otherSite = otherSite
    }
  }
  NavListMapper.storeNavList(navList)

  console.log(chrome)
  // chrome.runtime.sendMessage('closeCurrentTab')

  // getCurrentTab((tab) => {
  //   chrome.tabs.remove(tab.id, function () {})
  // })

  chrome.runtime.sendMessage('closeCurrentTab', function (response) {
    console.log('收到来自后台的回复：' + response)
  })
}

console.log(window)

$(function () {
  if ((/https:\/\/ai-bot.cn\/sites\/.*\.html/g).test(location.href)) {
    parseDetailPage()
  }
  if ((/https:\/\/ai-bot.cn/g).test(location.href)) {
    setTimeout(() => {
      startDownload()
    }, 3000)
  }
})

chrome.runtime.onMessage.addListener(
  function (message, sender, sendResponse) {
    console.log(message, sender, sendResponse)
    if (message === 'changeColor') {
      chrome.tabs.executeScript({
        code: 'document.body.style.backgroundColor="orange"'
      })
    }
    if (message === 'start-download') {
    //   let hrefList = startDownload()
    //   sendResponse(hrefList)

    }
    if (message === 'closeCurrentTab') {
      getCurrentTab((tab) => {
        chrome.tabs.remove(tab.id, function () {})
      })
    }
  })

console.log(window.$)
console.log('inject js ....', window.$('body'))

function getCurrentTab (callback) {
  let queryOptions = { active: true, lastFocusedWindow: true }
  chrome.tabs.query(queryOptions, ([tab]) => {
    if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError) }
    // `tab` will either be a `tabs.Tab` instance or `undefined`.
    callback(tab)
  })
}

window.closeCurrentTab = function () {
  chrome.tabs.getCurrent(function (tab) {
    chrome.tabs.remove(tab.id, function () { })
  })
}
